﻿using DTcms.API.Weixin.Common;
using DTcms.Common;
using DTcms.Model;
using DTcms.Web.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers
{
    public class WeixinController : ManageController
    {
        protected BaseApi _service = new BaseApi();
        protected int totalCount = 0;
        protected Model.manager managerModel = new Model.manager();
        protected string _action;
        protected int _id;

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            ActionResult result = View(EDIT_RESULT_VIEW);
            managerModel = GetAdminInfo();
            _action = DTRequest.GetQueryString("action");
            _id = DTRequest.GetQueryInt("id");
            ViewBag.action = _action;
            ViewBag.id = _id;
        }

        #region 页面创建
        [ChkAdminScript("weixin_custom_menu", DTEnums.ActionEnum.View)]
        public ActionResult Menu_List()
        {
            return View();
        }

        [ChkAdminScript("weixin_custom_menu", DTEnums.ActionEnum.View)]
        public ActionResult Menu_Edit()
        {
            Model.weixin_account model = new Model.weixin_account();
            if (_id == 0)
            {
                return ResultMsg("传输参数不正确！", "back");
            }
            model = _service.WeixinAccountInfo(_id);
            if (model == null)
            {
                return ResultMsg("记录不存在或已被删除！", "back");
            }
            return View();
        }

        [ChkAdminScript("weixin_response_text", DTEnums.ActionEnum.View)]
        public ActionResult Text_List()
        {
            return View();
        }

        [ChkAdminScript("weixin_response_text", DTEnums.ActionEnum.View)]
        public ActionResult Text_Edit()
        {
            Model.weixin_request_rule model = new Model.weixin_request_rule();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.WeiXinSoundInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }

        public ActionResult Subscribe_Edit()
        {
            int hideReqestType = 0;
            if (_action.ToLower() == "default")
            {
                ChkAdminLevel("weixin_subscribe_default", DTEnums.ActionEnum.View.ToString()); //检查权限
                ViewBag.RequestType = hideReqestType = 0;//默认回复
                ViewBag.Position = "默认回复";
            }
            else if (_action.ToLower() == "cancel")
            {
                ChkAdminLevel("weixin_subscribe_cancel", DTEnums.ActionEnum.View.ToString()); //检查权限
                ViewBag.RequestType = hideReqestType = 7;//取消关注
                ViewBag.Position = "默认回复";
            }
            else
            {
                ChkAdminLevel("weixin_subscribe_subscribe", DTEnums.ActionEnum.View.ToString()); //检查权限
                ViewBag.RequestType = hideReqestType = 6;//关注回复
                ViewBag.Position = "默认回复";
            }
            Model.weixin_request_rule ruleModel = new BLL.weixin_request_rule().GetModel(_id, hideReqestType); //获取规则
            return View(ruleModel);
        }

        [ChkAdminScript("weixin_response_sound", DTEnums.ActionEnum.View)]
        public ActionResult Sound_List()
        {
            return View();
        }

        [ChkAdminScript("weixin_response_sound", DTEnums.ActionEnum.View)]
        public ActionResult Sound_Edit()
        {
            Model.weixin_request_rule model = new Model.weixin_request_rule();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.WeiXinSoundInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }

        [ChkAdminScript("weixin_response_content", DTEnums.ActionEnum.View)]
        public ActionResult Response_List()
        {
            return View();
        }

        [ChkAdminScript("weixin_response_picture", DTEnums.ActionEnum.View)]
        public ActionResult Picture_List()
        {
            return View();
        }

        [ChkAdminScript("weixin_response_picture", DTEnums.ActionEnum.View)]
        public ActionResult Picture_Edit()
        {
            Model.weixin_request_rule model = new Model.weixin_request_rule();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.WeiXinPictureInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }

        [ChkAdminScript("weixin_account_manage", DTEnums.ActionEnum.View)]
        public ActionResult Account_List()
        {
            ViewBag.siteConfig = siteConfig;
            return View();
        }

        [ChkAdminScript("weixin_account_manage", DTEnums.ActionEnum.View)]
        public ActionResult Account_Edit()
        {
            Model.weixin_account model = new Model.weixin_account();
            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                if (_id == 0)
                {
                    return ResultMsg("传输参数不正确！", "back");
                }
                model = _service.WeixinAccountInfo(_id);
                if (model == null)
                {
                    return ResultMsg("记录不存在或已被删除！", "back");
                }
            }
            return View(model);
        }

        #region 数据绑定
        [ChkAdminJson("weixin_account_manage", DTEnums.ActionEnum.View)]
        public JsonResult AccountList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + AccountSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.WeixinAccountBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #region 组合SQL查询语句==========================
        protected string AccountSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (name like  '%" + _keywords + "%' or wxcode like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion

        [ChkAdminJson("weixin_response_picture", DTEnums.ActionEnum.View)]
        public JsonResult PictureList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "request_type=1 and response_type=2" + PictureSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.WeiXinPictureBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #region 组合SQL查询语句==========================
        protected string PictureSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (name like  '%" + _keywords + "%' or keywords like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion

        [ChkAdminJson("weixin_response_content", DTEnums.ActionEnum.View)]
        public JsonResult ResponseList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id > 0" + ResponseSqlTxt(keywords);
            string strOrder = "add_time desc,id desc";
            var resultList = _service.WeiXinResponseBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #region 组合SQL查询语句==========================
        protected string ResponseSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (openid like  '%" + _keywords + "%' or request_content like '%" + _keywords + "%' or reponse_content like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion

        [ChkAdminJson("weixin_response_sound", DTEnums.ActionEnum.View)]
        public JsonResult SoundList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "request_type=1 and response_type=3" + SoundSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.WeiXinSoundBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #region 组合SQL查询语句==========================
        protected string SoundSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (name like  '%" + _keywords + "%' or keywords like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion

        [ChkAdminJson("weixin_response_text", DTEnums.ActionEnum.View)]
        public JsonResult TextList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "request_type=1 and response_type=1" + TextSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.WeixinTextBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #region 组合SQL查询语句==========================
        protected string TextSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (name like  '%" + _keywords + "%' or keywords like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion

        [ChkAdminJson("weixin_custom_menu", DTEnums.ActionEnum.View)]
        public JsonResult MenuList(string keywords, int page = 1, int limit = 10)
        {
            string strWhere = "id>0" + MenuSqlTxt(keywords);
            string strOrder = "sort_id asc,id desc";
            var resultList = _service.WeixinMenuBind(strWhere, strOrder, page, limit);
            return Json(new { status = 1, msg = "", item = resultList.Items, totalCount = resultList.TotalItems });
        }
        #region 组合SQL查询语句==========================
        protected string MenuSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (name like  '%" + _keywords + "%' or wxcode like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion
        #endregion
        #endregion

        #region 删除
        [HttpPost]
        [ChkAdminJson("weixin_account_manage", DTEnums.ActionEnum.Delete)]
        public JsonResult AccountDelete(List<int> ids)
        {
            return _service.WeixinAccountDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("weixin_response_picture", DTEnums.ActionEnum.Delete)]
        public JsonResult PictureDelete(List<int> ids)
        {
            return _service.WeiXinPictureDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("weixin_response_content", DTEnums.ActionEnum.Delete)]
        public JsonResult ResponseDelete(List<int> ids)
        {
            return _service.WeiXinResponseDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("weixin_response_sound", DTEnums.ActionEnum.Delete)]
        public JsonResult SoundDelete(List<int> ids)
        {
            return _service.WeiXinSoundDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("weixin_response_text", DTEnums.ActionEnum.Delete)]
        public JsonResult TextDelete(List<int> ids)
        {
            return _service.WeixinTextDelete(ids);
        }

        [HttpPost]
        [ChkAdminJson("weixin_custom_menu", DTEnums.ActionEnum.Delete)]
        public JsonResult MenuDelete(List<int> ids)
        {
            return _service.WeixinMenuDelete(ids);
        }
        #endregion

        #region 字段修改
        [HttpPost]
        [ChkAdminJson("weixin_account_manage", DTEnums.ActionEnum.Edit)]
        public JsonResult AccountFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.weixin_account bll = new BLL.weixin_account();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("weixin_response_picture", DTEnums.ActionEnum.Edit)]
        public JsonResult PictureFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("weixin_response_sound", DTEnums.ActionEnum.Edit)]
        public JsonResult SoundFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }

        [HttpPost]
        [ChkAdminJson("weixin_response_text", DTEnums.ActionEnum.Edit)]
        public JsonResult TextFiledSave(string field, int value, int id = 0)
        {
            if (string.IsNullOrEmpty(field) || id == 0)
            {
                return Json(new { status = 0, msg = "参数错误！" });
            }
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            if (bll.UpdateFile("id=" + id, field + "=" + value))
            {
                return Json(new { status = 1, msg = "修改成功！" });
            }
            return Json(new { status = 0, msg = "修改失败！" });
        }
        #endregion

        #region 保存
        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult AccountSave(Model.weixin_account t)
        {
            SaveModel save = _service.WeixinAccountSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../weixin/account_list";
            return Json(save);
        }

        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult PictureSave(Model.weixin_request_rule t)
        {
            SaveModel save = _service.WeiXinPictureSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../weixin/picture_list";
            return Json(save);
        }

        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult SoundSave(Model.weixin_request_rule t)
        {
            SaveModel save = _service.WeiXinSoundSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../weixin/sound_list";
            return Json(save);
        }

        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult SubscribeSave(string txtContent)
        {
            SaveModel save = _service.WeiXinSubscribeSave(_action, _id, txtContent);
            save.url = save.status == 0 ? "back" : "../weixin/subscribe_edit?action=" + _action + "&id=" + _id;
            return Json(save);
        }

        public ActionResult SubscribeDel(int type)
        {
            SaveModel save = _service.SubscribeDel(_action, _id, type);
            save.url = save.status == 0 ? "back" : "../weixin/subscribe_edit?action=" + _action + "&id=" + _id;
            return Json(save);
        }

        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult TextSave(Model.weixin_request_rule t)
        {
            SaveModel save = _service.WeixinTextSave(_action, _id, t);
            save.url = save.status == 0 ? "back" : "../weixin/text_list";
            return Json(save);
        }

        [HttpPost, CustomValidateAntiForgeryToken]
        public ActionResult MenuSave()
        {
            SaveModel save = _service.WeixinMenuSave(_id);
            save.url = save.status == 0 ? "back" : "../weixin/menu_list";
            return Json(save);
        }
        #endregion

        [ChkAdminScript("weixin_custom_menu", DTEnums.ActionEnum.View)]
        public JsonResult GetMenu()
        {
            CRMComm wxComm = new CRMComm(); //获取AccessToKen类
            string error = string.Empty;
            string accessToken = wxComm.GetAccessToken(_id, out error);

            if (!string.IsNullOrEmpty(error))
            {
                return Json(new { status = 0, msg = error });
            }
            var result = Senparc.Weixin.MP.CommonAPIs.CommonApi.GetMenu(accessToken);
            if (result == null)
            {
                return Json(new { status = 0, msg = "菜单不存在或验证失败！" });
            }
            return Json(new { status = 1, msg = result });
        }
    }
}
